package party.lovey.remote.controller;

import party.lovey.remote.amq.Receiver;
import party.lovey.remote.utils.Consts;
import party.lovey.remote.utils.ImageUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

/**
 * Created by huhaichao on 2017/4/26.
 */
public class ControlFrame extends JFrame {

    private BufferedImage bufferedImage;
    private JPanel jPanel;

    public ControlFrame() {
        this.setBounds(0, 0, 800, 600);
        this.setContentPane(new ScrollPane());
        this.setVisible(true);
        this.setTitle("远程桌面--控制端");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Point point = e.getPoint();
                Control.sendPoint(ControlFrame.this.revertPoint(point));
                super.mouseClicked(e);
            }
        });

         jPanel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                Graphics2D g2d = (Graphics2D) g;
                if (bufferedImage != null) {
                    g2d.drawImage(bufferedImage, 0, 0, ControlFrame.this.jPanel.getWidth(), ControlFrame.this.jPanel.getHeight(),
                            0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), null);
                }
            }
        };

        this.add(jPanel);

        Thread t=new Thread(new Runnable(){
            @Override
            public void run() {
                while(true){
                    jPanel.repaint();
                    jPanel.validate();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }

                }
            }

        });
        t.start();

    }

    public Point revertPoint(Point point) {
        if (bufferedImage != null) {
            int x = (int) (ControlFrame.this.bufferedImage.getWidth() * 1.0 / ControlFrame.this.getWidth() * point.x);
            int y = (int) (ControlFrame.this.bufferedImage.getHeight() * 1.0 / ControlFrame.this.getHeight() * point.y);
            point.setLocation(x, y);
        }

        return point;
    }






    public void onReceiveImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }


    public static void main(String[] args) throws InterruptedException {
        ControlFrame controlFrame = new ControlFrame();
        while (true){
            BufferedImage bufferedImage = ImageUtil.fromBytes(Receiver.receiveBinaryMessage(Consts.MESSAGE_IMAGE_SCREEN));
            controlFrame.onReceiveImage(bufferedImage);
            Thread.sleep(100);
        }
    }
}
